<template>
	<div>
		<el-form class="base_form" :model="submitForm" :rules="rules" ref="ruleForm" label-width="200px">
			<el-form-item label="商品品类" prop="category_id">
				<el-select v-model="submitForm.category_id" placeholder="请选择商品品类" @change="categoryChange">
					<el-option v-for="item in categoryList" :key="item.category_id" :label="item.name"
						:value="item.category_id"></el-option>
				</el-select>
				<p class="color-999 inline-block" style="margin-left:15px">未申请商品品类？点击立即<el-button v-if="$hasMethod('#apply')"
						type="text" @click="$router.push({name:'goodsCategoryApply'})">申请品类</el-button>
				</p>
			</el-form-item>
			<el-form-item label="商品名称" prop="goods_name">
				<el-input style="width:100%" v-model="submitForm.goods_name" maxlength="50" show-word-limit
					placeholder="请输入商品名称"></el-input>
			</el-form-item>
			<el-form-item label="推广关键字">
				<el-input style="width:100%" v-model="submitForm.spread_title" maxlength="50" show-word-limit
					placeholder="请输入推广关键字，以中文逗号隔开"></el-input>
			</el-form-item>
			<el-form-item label="商品参数">
				<div class="flex flex-wrap params_wrap">
					<template v-for="(param, index) in goodsParams">
						<div :key="index">
							<label><i v-if="param.must_is" class="required-icon"
									style="margin-right:5px">*</i>{{param.field_title}}:</label>
							<template v-if="param.field_type==1">
								<!-- 文本框 -->
								<el-input v-model="param.field_val" placeholder="请输入"></el-input>
							</template>
							<template v-if="param.field_type==2">
								<!-- 下拉单选 -->
								<el-select v-model="param.field_val" placeholder="请选择">
									<el-option v-for="(item, index) in param.field_list" :key="index" :label="item"
										:value="item"></el-option>
								</el-select>
							</template>
							<template v-if="param.field_type==3">
								<!-- 下拉多选 -->
								<el-select v-model="param.field_val" placeholder="请选择" multiple>
									<el-option v-for="(item, index) in param.field_list" :key="index" :label="item"
										:value="item"></el-option>
								</el-select>
							</template>
						</div>
					</template>
				</div>
			</el-form-item>
			<el-form-item label="新旧" prop="new_grade">
				<el-radio-group v-model="submitForm.new_grade">
					<el-radio v-for="(val, key) in initData.new_grade" :key="key" :label="key">{{val}}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="租赁标签">
				<div v-for="item in initData.rent_label" :key="item" class="inline-block pointer rent_tag"
					:class="{'active':isTagCheck(item)}" @click="handleTagClick(item)">
					<span class="inline-block color-666">{{item}}</span>
					<span class="inline-block text-center"><i v-if="isTagCheck(item)"
							class="el-icon-check blue-font vertical-middle check_icon"></i></span>
				</div>
			</el-form-item>
			<el-form-item label="商品封面" prop="imgurl">
				<crop-upload ref="coverUpload" show-type="photo" :fixScale="true" :is-square="true" :always-crop="true"
					:fixedBox="false" :init-val="submitForm.imgurl" wrapper-width="120px" wrapper-height="120px"
					:photo-width="120" :photo-height="120" :autoCropWidth="150" :autoCropHeight="150" cropperWidth="400px"
					cropperHeight="400px" dialogWidth="600px" :min-width="750" :min-height="750" :enlarge="5"
					@setVal="setUrl"></crop-upload>
				<div class="color-999">注：尺寸为750*750px及以上正方形，图片要求为纯白色底图
					<el-popover placement="right" width="400" trigger="hover">
						<div class="img_exp">
							<h5>商品封面图片示例</h5>
							<div class="exp_wrap">
								<p class="item">
									<el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp1.png')"></el-image>
									<span><i class="green-font el-icon-success"></i>推荐</span>
								</p>
								<p class="item">
									<el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp2.png')"></el-image>
									<span><i class="red-font el-icon-error"></i>不推荐</span>
								</p>
								<p class="item">
									<el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp3.png')"></el-image>
									<span><i class="red-font el-icon-error"></i>不推荐</span>
								</p>
							</div>
							<p class="red-font">注：图片要求750*750像素以上的正方形图片；<br />注：上传封面图片要求纯白色底图；<br />注：精品纯白色底图可上首页推荐位！</p>
						</div>
						<el-button type="text" slot="reference">图片示例></el-button>
					</el-popover>
				</div>
			</el-form-item>
			<el-form-item label="商品图片" prop="carousel_img">
				<crop-upload ref="cropUpload" :sort="true" :multiple="true" :always-crop="true" show-type="photo"
					:fixScale="true" :fixedBox="false" :is-square="true" :init-val="submitForm.carousel_img" wrapper-width="120px"
					wrapper-height="120px" :autoCropWidth="150" :autoCropHeight="150" cropperWidth="400px" cropperHeight="400px"
					dialogWidth="600px" :enlarge="5" :maxNum="8" :photo-width="120" :photo-height="120" :min-width="750"
					:min-height="750" @setVal="bannerChange"></crop-upload>
			</el-form-item>
			<el-form-item label="商品详情">
				<div class="editor_wrap">
					<text-editor v-model="submitForm.goods_content"></text-editor>
				</div>
			</el-form-item>
			<el-form-item label="租赁方式" prop="pact_type">
				<el-radio-group v-model="submitForm.pact_type">
					<el-radio v-for="(val, key) in initData.pact_type" :key="key" :label="key">{{val}}</el-radio>
				</el-radio-group>
				<p class="type_tip">
					<template v-if="submitForm.pact_type==1">
						<span>固定租期的芝麻信用授权可扣款金额=商品套餐押金+总租金</span><br />商品设置固定租期后，承租人须待租赁期满后才能退还租赁物。固定租期无法使用花呗分期功能。
					</template>
					<template v-if="submitForm.pact_type==2">
						<span>租完即送的芝麻信用授权可扣款金额=总租金</span><br />商品设置租完即送后，租赁期内承租人不得单方面解除协议提前退还租赁物，承租人须按订单约定按期支付租金。租完即送可使用花呗分期功能。
					</template>
					<template v-if="submitForm.pact_type==3">
						<span>随租随还的芝麻信用授权可扣款金额=商品套餐押金+总租金</span><br />商品设置随租随还后，承租人可以随时退还租赁物。随租随还无法使用花呗分期功能。
					</template>
				</p>
			</el-form-item>
			<el-form-item label="服务城市" prop="province">
				<el-cascader clearable filterable placeholder="请选择" v-model="submitForm.province" :options="areaList"
					:props="optionProps" separator="-"></el-cascader>
			</el-form-item>
			<el-form-item label="租赁地址">
				<el-select v-model="submitForm.service_address" clearable placeholder="请选择">
					<el-option v-for="(item, index) in initData.shop_address" :key="index" :label="item.address"
						:value="item.address">
					</el-option>
				</el-select>
				<p class="color-999 inline-block" style="margin-left:15px">没有租赁地址？点击添加<el-button type="text"
						@click="goToRentAd">租赁地址</el-button>
				</p>
			</el-form-item>
			<!-- <el-form-item label="运费">
        <el-input
          v-model="submitForm.transfer_cost"
          clearable
          @input="val=>changeNumberInput('transfer_cost',val)"
        >
        </el-input>
      </el-form-item> -->
			<el-form-item label="配送方式" prop="send_out" style="margin-bottom:0px">
				<div class="flex align-center">
					<label class="text-right" style="width:40px;margin-right:20px"><span class="required-icon">*</span>寄出</label>
					<el-radio-group v-model="submitForm.send_out">
						<el-radio v-for="(val, key) in initData.send_out" :key="key" :label="key">{{val}}</el-radio>
					</el-radio-group>
				</div>
			</el-form-item>
			<el-form-item>
				<div class="flex align-center">
					<label class="text-right" style="width:40px;margin-right:20px">归还</label>
					<el-radio-group v-model="submitForm.return">
						<el-radio v-for="(val, key) in initData.return" :key="key" :label="key">{{val}}</el-radio>
					</el-radio-group>
				</div>
			</el-form-item>
		</el-form>
		<div class="fix-footer-btns">
			<div class="flex justify-center align-center">
				<label style="margin-right:20px"><i class="required-icon" style="margin-right:5px">*</i>商品审核后状态:</label>
				<el-radio v-model="status" :label="1">商品上架</el-radio>
				<el-radio v-model="status" :label="2">商品下架</el-radio>
			</div>
			<el-divider></el-divider>
			<div>
				<template v-if="!editId">
					<el-button size="small" v-if="$hasMethod('#saveBaseDraft')" @click="saveToDraft">保存草稿</el-button>
					<el-button size="small" v-if="$hasMethod('#addBase')" type="primary" @click="nextStep">下一步</el-button>
				</template>
				<template v-else>
					<el-button size="small" @click="$router.go(-1)">返回</el-button>
					<el-button size="small" type="primary" v-if="$hasMethod('#editBase')" @click="save">保存</el-button>
					<el-button size="small" type="warning" v-if="$hasMethod('#submit')&&!hideAuditBtn"
						@click="submitAudit">提交审核</el-button>
				</template>
			</div>
		</div>
	</div>
</template>

<script>
	import cropUpload from "@/components/cropUpload";
	import textEditor from "@/components/wangEditor";
	import {
		getAreas
	} from "@/api/index";
	import {
		getShopCategory,
		getGoodsRentData,
		getGoodsParameter,
		addGoodsData,
		getGoodsData,
		editGoodsData,
		getGoodsAndSetmeal,
		goodsSubmitReview
	} from "@/api/goods";
	export default {
		components: {
			cropUpload,
			textEditor
		},
		props: ['editId', 'activeTab', 'draftId'],
		data() {
			return {
				submitForm: {
					category_id: null,
					goods_name: "",
					spread_title: "",
					new_grade: '100',
					rent_label: [],
					imgurl: "",
					carousel_img: [],
					goods_content: "",
					pact_type: '1',
					province: [],
					service_address: "",
					send_out: '1',
					return: '1',
					transfer_cost: ""
				},
				rules: {
					carousel_img: [{
						required: true,
						message: '请上传商品图片',
						trigger: 'blur'
					}],
					province: [{
						required: true,
						message: '请选择服务城市',
						trigger: 'change'
					}, ],
					category_id: [{
						required: true,
						message: '请选择商品品类',
						trigger: 'change'
					}],
					goods_name: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}, ],
					imgurl: [{
						required: true,
						message: '请上传商品封面',
						trigger: 'change'
					}, ],
					new_grade: [{
						required: true,
						message: '请选择新旧程度',
						trigger: 'change'
					}]
				},
				areaList: [], // 服务城市
				adsList: [], // 租赁地址
				categoryList: [], //品类列表
				optionProps: {
					value: 'id',
					label: 'name',
					expandTrigger: 'hover',
					children: 'sub'
				},
				initData: {
					new_grade: {}, // 新旧程度
					rent_label: [], // 标签
					pact_type: [], // 租赁方式
					send_out: {}, // 寄出
					return: {}, // 归还
					shop_address: [] // 租赁地址
				},
				goodsParams: [], // 商品参数
				status: 2, // 商品审核后上架/下架
				hideAuditBtn: false
			}
		},
		methods: {
			goToRentAd() {
				this.$confirm('跳转前请先保存草稿，确认继续跳转吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
				}).then(() => {
					this.$router.push({
						name: 'shopRentAd'
					});
				}).catch(() => {});
			},
			// 提交审核
			submitAudit() {
				goodsSubmitReview(this.editId).then(res => {
					this.$router.push({
						name: 'goodsSuccess',
						params: {
							goodsId: this.editId,
							isEdit: true
						}
					});
				})
			},
			// 保存草稿
			saveToDraft() {
				if (!this.submitForm.category_id || !this.submitForm.goods_name) {
					this.$message({
						message: "商品品类和商品名称不能为空",
						type: "warning"
					});
					return;
				}
				const data = {
					...this.submitForm,
					status: this.status,
					operation_type: 1
				};
				data.rent_label = data.rent_label.join(',');
				data.province_id = data.province && data.province[0] ? data.province[0] : "";
				data.show_ity = data.province && data.province[1] ? data.province[1] : "";
				data.carousel_img = data.carousel_img.join(',');
				data.custom = this.goodsParams.map(item => {
					return {
						'field_title': item.field_title,
						'field_val': item.field_type != 3 ? item.field_val : item.field_val.join(',')
					}
				});
				delete data.province;
				// console.log(data);
				if (!sessionStorage.getItem('goodsId')) {
					// 没有商品id，新增
					addGoodsData(data).then(res => {
						sessionStorage.setItem('goodsId', res.goods_id);
						this.$message({
							message: "保存成功",
							type: "success"
						});
					})
				} else {
					// 有商品id，编辑
					data.goods_id = sessionStorage.getItem('goodsId');
					editGoodsData(data).then(res => {
						this.$message({
							message: "保存成功",
							type: "success"
						});
					})
				}
			},
			// 获取品类对应的商品参数
			async categoryChange(val) {
				if (!val) {
					return;
				}
				await getGoodsParameter(val).then(res => {
					this.goodsParams = [];
					for (let item of res) {
						item.field_val = "";
						item.field_list = item.field_list.split(',');
						this.goodsParams.push({
							...item
						});
					}
				})
			},
			save() {
				const that = this;
				this.$confirm('商品信息变更需要平台审核，审核时间1个工作日，确定修改商品？', '修改商品', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
				}).then(() => {
					that.$refs['ruleForm'].validate((valid) => {
						if (valid) {
							// 检查商品参数必填项
							for (let item of that.goodsParams) {
								if (item.must_is && (!item.field_val || item.field_val.length === 0)) {
									that.$message({
										message: "商品参数" + item.field_title + "必填",
										type: "warning"
									});
									return;
								}
							}
							const data = {
								goods_id: that.editId,
								...that.submitForm,
								status: that.status,
								operation_type: 3
							};
							data.rent_label = data.rent_label.join(',');
							data.province_id = data.province[0];
							data.show_ity = data.province[1];
							data.carousel_img = data.carousel_img.join(',');
							data.custom = that.goodsParams.map(item => {
								return {
									'field_title': item.field_title,
									'field_val': item.field_type != 3 ? item.field_val : item.field_val.join(',')
								}
							});
							delete data.province;
							// console.log(data);
							editGoodsData(data).then(res => {
								that.$message({
									message: "保存成功",
									type: "success"
								});
								// that.$router.push({ name: 'goodsSuccess', params: { goodsId: that.editId, isEdit: true } });
							})
						} else {
							that.$message({
								message: "请检查表单错误",
								type: "error"
							});
							return false;
						}
					});
				}).catch(() => {});
			},
			nextStep() {
				this.$refs['ruleForm'].validate((valid) => {
					if (valid) {
						// 检查商品参数必填项
						for (let item in this.goodsParams) {
							if (item.must_is && !item.field_val) {
								this.$message({
									message: "商品参数" + item.field_title + "必填",
									type: "warning"
								});
								return;
							}
						}
						const data = {
							...this.submitForm,
							status: this.status,
							operation_type: 3
						};
						data.rent_label = data.rent_label.join(',');
						data.province_id = data.province[0];
						data.show_ity = data.province[1];
						data.carousel_img = data.carousel_img.join(',');
						data.custom = this.goodsParams.map(item => {
							return {
								'field_title': item.field_title,
								'field_val': item.field_type != 3 ? item.field_val : item.field_val.join(',')
							}
						});
						delete data.province;
						// console.log(data);
						if (!sessionStorage.getItem('goodsId')) {
							// 没有商品id，新增
							addGoodsData(data).then(res => {
								sessionStorage.setItem('goodsId', res.goods_id);
								this.$emit('changeTab');
							})
						} else {
							// 有商品id，编辑
							data.goods_id = sessionStorage.getItem('goodsId');
							editGoodsData(data).then(res => {
								this.$emit('changeTab');
							})
						}
					} else {
						this.$message({
							message: "请检查表单错误",
							type: "error"
						});
						return false;
					}
				});
			},
			changeNumberInput(key, value) {
				const pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
				// 不符合正整数时
				if (!pattern.test(value)) {
					// input 框绑定的内容为空
					this.submitForm[key] = ''
				}
			},
			bannerChange(val, type) {
				if (type === 'sort') {
					this.submitForm.carousel_img = val;
					return
				}
				if (type === 'del') {
					this.submitForm.carousel_img.splice(val, 1);
				} else {
					this.submitForm.carousel_img.push(val);
				}
				this.$refs.cropUpload.sortList = this.submitForm.carousel_img;
			},
			setUrl(val) {
				this.submitForm.imgurl = val;
			},
			handleTagClick(tag) {
				const index = this.submitForm.rent_label.findIndex(item => item === tag);
				if (index > -1) {
					this.submitForm.rent_label.splice(index, 1);
				} else {
					this.submitForm.rent_label.push(tag);
				}
			},
			// 判断标签是否选中
			isTagCheck(tag) {
				return this.submitForm.rent_label.findIndex(item => item === tag) > -1
			},
			init() {
				getShopCategory().then(res => {
					this.categoryList = res || [];
				})
				getAreas().then(res => {
					this.areaList = res ? res[0].sub : [];
				})
				getGoodsRentData().then(res => {
					if (res) {
						this.initData = res;
					}
				})
			},
			getData() {
				if (this.editId) {
					// 编辑
					getGoodsData(this.editId).then(async res => {
						this.hideAuditBtn = res.ischeck == 3;
						for (let key in this.submitForm) {
							if (key === 'carousel_img') {
								this.submitForm[key] = res.carousel_images ? res.carousel_images.split(',') : [];
								this.$refs.cropUpload.sortList = this.submitForm.carousel_img;
							} else if (key === 'goods_name') {
								this.submitForm[key] = res.title;
							} else if (key === 'province') {
								this.submitForm[key] = [res.province_id, res.show_ity];
							} else if (key === 'rent_label') {
								this.submitForm[key] = res.rent_label.split(',');
							} else if (key === 'pact_type') {
								this.submitForm[key] = res.pact_type + '';
							} else if (key === 'return') {
								this.submitForm[key] = res.convey_type2 + '';
							} else if (key === 'send_out') {
								this.submitForm[key] = res.convey_type1 + '';
							} else if (res[key]) {
								this.submitForm[key] = res[key];
							}
						}
						this.status = res.status;
						await this.categoryChange(res.category_id);
						for (let item of res.attribute) {
							for (let param of this.goodsParams) {
								if (item.field_title === param.field_title) {
									param.field_val = param.field_type == 3 ? item.field_val.split(',') : item.field_val;
								}
							}
						}
					})
				} else if (this.draftId) {
					getGoodsAndSetmeal(this.draftId).then(async res => {
						// console.log(res);
						sessionStorage.setItem('goodsId', res.id);
						for (let key in this.submitForm) {
							if (key === 'carousel_img') {
								this.submitForm[key] = res.carousel_images ? res.carousel_images.split(',') : [];
								this.$refs.cropUpload.sortList = this.submitForm.carousel_img;
							} else if (key === 'goods_name') {
								this.submitForm[key] = res.title;
							} else if (key === 'province') {
								this.submitForm[key] = res.province_id && res.show_ity ? [res.province_id, res.show_ity] : [];
							} else if (key === 'rent_label') {
								this.submitForm[key] = res.rent_label ? res.rent_label.split(',') : [];
							} else if (key === 'pact_type') {
								this.submitForm[key] = res.pact_type + '';
							} else if (key === 'return') {
								this.submitForm[key] = res.convey_type2 + '';
							} else if (key === 'send_out') {
								this.submitForm[key] = res.convey_type1 + '';
							} else if (res[key]) {
								this.submitForm[key] = res[key];
							}
						}
						this.status = res.status || 2;
						await this.categoryChange(res.category_id);
						for (let item of res.attribute) {
							for (let param of this.goodsParams) {
								if (item.field_title === param.field_title) {
									param.field_val = param.field_type == 3 ? item.field_val.split(',') : item.field_val;
								}
							}
						}
						this.setMealList(res.setmeal);
					})
				} else {
					// 新增
					if (sessionStorage.getItem('baseInfo')) {
						const data = JSON.parse(sessionStorage.getItem('baseInfo'));
						// console.log(data);
						this.submitForm = {
							...data.formData
						};
						this.goodsParams = [...data.goodsParams];
					}
					this.status = parseInt(sessionStorage.getItem('goodsStatus')) || 2;
				}
			},
			setMealList(mealList) {
				const list = mealList.map(item => {
					const formData = {
						setmeal_id: "",
						title: "",
						lease_set: 1,
						is_huabei: 2,
						huabei_data: [{
							lease_term: "",
							rent_total: "",
							three_bear: "",
							three_fee: "",
							six_bear: "",
							six_fee: "",
							twelve_bear: "",
							twelve_fee: ""
						}],
						quantity: "",
						foregift: "",
						is_buy_out: 1,
						price: "",
						start_date: ""
					};
					let monthList = [{
						lease_time: null,
						lease_price: ""
					}];
					let dayList = [{
						lease_time: "",
						lease_price: ""
					}];
					let customList = [];
					for (let key in formData) {
						if (key === 'huabei_data') {
							if (item.is_huabei == 1) {
								formData[key] = item[key];
							}
						} else if (key === 'setmeal_id') {
							formData[key] = item.id;
						} else {
							formData[key] = item[key];
						}
					}
					if (item.lease_set == 1) {
						monthList = item.spec;
					} else if (item.lease_set == 2) {
						dayList = item.spec;
					} else {
						customList = item.spec;
					}
					return {
						formData,
						monthList,
						dayList,
						customList
					}
				});
				sessionStorage.setItem('mealInfo', JSON.stringify(list));
				this.$parent.mealTabs = JSON.parse(sessionStorage.getItem('mealInfo')).length;
			}
		},
		mounted() {
			this.init();
			this.getData();
		},
		beforeDestroy() {
			if (!this.editId) {
				sessionStorage.setItem('baseInfo', JSON.stringify({
					formData: this.submitForm,
					goodsParams: this.goodsParams
				}));
				sessionStorage.setItem('goodsStatus', this.status);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.editor_wrap {
		width: 700px;

		/deep/.text {
			height: 360px;
			overflow: auto;
		}
	}

	.base_form {
		padding: 30px 120px 30px 0;
	}

	.params_wrap {
		width: 100%;
		padding: 20px;
		background-color: $gray-content;

		label {
			display: inline-block;
			width: 120px;
			text-align: right;
			margin-right: 10px;
		}

		&>div {
			margin-bottom: 10px;
		}
	}

	.type_tip {
		color: #999999;
		line-height: 22px;

		span {
			color: #ff4146;
		}
	}

	.rent_tag {
		height: 30px;
		line-height: 28px;
		border: 1px solid #eeeeee;
		border-radius: 3px;

		span:first-child {
			padding-left: 5px;
			padding-right: 5px;
			background: #d2d2d2;
		}

		span:last-child {
			width: 35px;
		}

		&:not(:last-of-type) {
			margin-right: 15px;
		}

		&.active {
			border: 1px solid $mainBlue;

			span:first-child {
				color: #ffffff;
				background: $mainBlue;
			}
		}

		.check_icon {
			font-size: 26px;
			font-weight: bold;
		}
	}

	.exp_wrap {
		display: flex;
		margin-top: 18px;
		margin-bottom: 18px;

		.item {
			display: flex;
			width: 33%;
			align-items: center;
			flex-direction: column;

			.el-image {
				border: 1px solid #eeeeee;
			}

			span {
				margin-top: 10px;

				i {
					font-size: 20px;
					vertical-align: middle;
					margin-right: 3px;
				}
			}
		}
	}

	.fix-footer-btns {
		.el-divider {
			background-color: #eeeeee;
			width: 95%;
			margin: 15px auto;
		}
	}
</style>